package com.kunya.product.service.impl.cart;

import com.google.common.collect.Lists;
import com.google.common.base.Splitter;
import com.kunya.common.common.Const;
import com.kunya.common.common.ResponseCode;
import com.kunya.common.common.ServerResponse;
import com.kunya.common.util.BigDecimalUtil;
import com.kunya.common.util.PropertiesUtil;
import com.kunya.product.dao.cart.CartMapper;
import com.kunya.product.dao.product.ProductMapper;
import com.kunya.product.dao.specification.ProductSpecificationMapper;
import com.kunya.product.po.Cart;
import com.kunya.product.po.Product;
import com.kunya.product.po.ProductSpecification;
import com.kunya.product.service.cart.ICartService;
import com.kunya.product.vo.CartProductVo;
import com.kunya.product.vo.CartVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
 * @author zp
 * @Description: 购物车service
 * @date 2018/5/28 11:25
 */
@Slf4j
@Service("iCartService")
public class CartServiceImpl implements ICartService {

    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private ProductSpecificationMapper productSpecificationMapper;
    @Autowired
    private ProductMapper productMapper;



    /**
     * @author zp
     * @Description: 向购物车中添加商品，并返回购物车列表
     * @param
     * @date 2018/5/28 14:39
     */
    @Override
    @Transactional
    public ServerResponse<CartVo> add(Long userId, Long productSpecNumber, Integer count,String tablePrefix) {
        if (productSpecNumber == null || count == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),
                    ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        Cart cart = cartMapper.selectCartByUserIdProductSpecNumber(productSpecNumber, userId,tablePrefix);
        if (cart == null) {
            // 说明该产品不再购物车中，那么将产品加入购物车中
            Cart cartitem = new Cart();
            // 设置加入购物车产品自动为选中状态
            cartitem.setCheckStatus(Const.Cart.CHECKED);
            cartitem.setBuyNumber(count);
            cartitem.setUserId(userId);
            cartitem.setProductSpecNumber(productSpecNumber);
            cartMapper.insert(cartitem,tablePrefix);

        } else {
            // 表示该产品已经在购物车中，产品数量相加
            count = cart.getBuyNumber() + count;
            cart.setBuyNumber(count);
            cartMapper.updateByPrimaryKeySelective(cart,tablePrefix);
        }
        return this.list(userId,tablePrefix);
    }

    @Override
    @Transactional
    public ServerResponse<CartVo> update(Long userId, Long productSpecNumber, Integer count,String tablePrefix) {

        if (productSpecNumber==null||count==null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),
                    ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        Cart cart=cartMapper.selectCartByUserIdProductSpecNumber(productSpecNumber,userId,tablePrefix);
        if (cart!=null){
            cart.setBuyNumber(count);
        }
        cartMapper.updateByPrimaryKey(cart,tablePrefix);
        return this.list(userId,tablePrefix);
    }

    @Override
    public ServerResponse<CartVo> deleteProduct(Long userId, String productSpecNumbers,String tablePrefix) {
        //与前端约定将所有要删除的商品规格属性编号以英文半角逗号分隔
        List<String> productList=Splitter.on(",").splitToList(productSpecNumbers);
        if (CollectionUtils.isEmpty(productList)) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),
                    ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        cartMapper.deleteByUserIdAndProductSpecNumbers(userId, productList,tablePrefix);
        return this.list(userId,tablePrefix);
    }


    /**
     * @author zp
     * @Description: 选择或者反选
     * @param
     * @date 2018/5/28 16:37
     */
    @Override
    public ServerResponse<CartVo> selectOrUnSelect(Long userId, Long productSpecNumber, Byte checked,String tablePrefix) {
        cartMapper.checkedOrUncheckedProduct(userId, productSpecNumber,checked,tablePrefix);
        return this.list(userId,tablePrefix);
    }

    @Override
    /**
     * @author zp
     * @Description: 获取购物车中商品数量。
     * @param
     * @date 2018/5/28 16:40
     */
    public ServerResponse<Integer> getCartProductCount(Long userId,String tablePrefix) {
        if(userId==null) {
            return ServerResponse.createBySuccess(0);
        }
        return ServerResponse.createBySuccess(cartMapper.selectCartProductCount(userId,tablePrefix));
    }

    @Override
    public ServerResponse<CartVo> list(Long userId,String table_prefix) {
        CartVo cartVo = this.getCartVoLimit(userId,table_prefix);
        return ServerResponse.createBySuccess(cartVo);
    }

    /**
     * @param
     * @author zp
     * @Description: 根据用户id查询 购物车列表 返回vo对象list
     * @date 2018/5/28 13:15
     */
    private CartVo getCartVoLimit(Long userId,String tablePrefix) {
        CartVo cartVo = new CartVo();
        List<Cart> cartList = cartMapper.selectCartByUserId(userId,tablePrefix);
        List<CartProductVo> cartProductVoList = Lists.newArrayList();
        BigDecimal cartTotalPrice = new BigDecimal("0");
        if (CollectionUtils.isNotEmpty(cartList)) {
            for (Cart cartItem : cartList) {
                CartProductVo cartProductVo = new CartProductVo();
                cartProductVo.setCartId(cartItem.getCartId());
                cartProductVo.setUserId(userId);
                cartProductVo.setProductSpecNumber(cartItem.getProductSpecNumber());

                ProductSpecification productSpecification = productSpecificationMapper.selectByProductSpecNumber(cartItem.getProductSpecNumber(),tablePrefix);
                if (productSpecification != null) {
                    //根据商品id获取商品Product
                    Product product=productMapper.selectByPrimaryKey(productSpecification.getProductId(),tablePrefix);
                    //todo  商品标题？
                       cartProductVo.setProductImgurl(product.getPicImg());//商品图片链接
                       cartProductVo.setProductName(product.getName());//商品名称
//                    cartProductVo.setProductSubtitle(product.getSubtitle());
                    cartProductVo.setProductStatus(productSpecification.getStatus());//商品状态
                    cartProductVo.setProductPrice(productSpecification.getPrice());//商品单价
                    cartProductVo.setProductStock(productSpecification.getStock());//商品库存
                    // 判断库存
                    int buyLimitCount = 0;
                    // 当产品库存大于用户要向购物车中添加的数量，设置限制库存为成功
                    if (productSpecification.getStock() >= cartItem.getBuyNumber()) {
                        buyLimitCount = cartItem.getBuyNumber();
                        cartProductVo.setLimitQuantity(Const.Cart.LIMIT_NUM_SUCCESS);
                    } else {
                        // 当产品库存小于用户要向购物车中添加的数量，设置限制库存为失败（可供前端，提示用户数量不足）
                        buyLimitCount = productSpecification.getStock();
                        cartProductVo.setLimitQuantity(Const.Cart.LIMIT_NUM_FAIL);
                        // 购物车中更新有效库存，有效库存为产品库存
                        Cart cartForQuantity = new Cart();
                        cartForQuantity.setCartId(cartItem.getCartId());
                        cartForQuantity.setBuyNumber(buyLimitCount);
                        cartMapper.updateByPrimaryKeySelective(cartForQuantity,null);
                    }
                    cartProductVo.setBuyNumber(buyLimitCount);
                    // 计算总价（单个产品的总价）
                    cartProductVo.setProductTotal(BigDecimalUtil.mul(productSpecification.getPrice().doubleValue(), cartProductVo.getBuyNumber()));
                    cartProductVo.setCheckStatus(cartItem.getCheckStatus());

                }

                if (cartItem.getCheckStatus() == Const.Cart.CHECKED) {
                    // 如果已经勾选,增加到整个的购物车总价中
                    cartTotalPrice = BigDecimalUtil.add(cartTotalPrice.doubleValue(), cartProductVo.getProductTotal().doubleValue());
                }
                cartProductVoList.add(cartProductVo);
            }
        }

        cartVo.setCartTotalPrice(cartTotalPrice);
        cartVo.setCartProductVoList(cartProductVoList);
        cartVo.setAllChecked(this.getAllCheckedStatus(userId,tablePrefix));//设置是否全选
        cartVo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix"));
        return cartVo;
    }

    /**
     * @author zp
     * @Description: 判断购物车是否为全选状态
     * @param
     * @date 2018/5/28 14:37
     */
    private boolean getAllCheckedStatus(Long userId,String tablePrefix) {
        if (userId == null) {
            return false;
        }
        return cartMapper.selectCartProductCheckedStatusByUserId(userId,tablePrefix) == 0;

    }

}
